package com.saku.uiprojecttest.activities;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.saku.uiprojecttest.R;
import com.saku.uiprojecttest.SakuApplication;
import com.saku.uiprojecttest.bean.User;
import com.saku.uiprojecttest.http.NetManager;

import javax.inject.Inject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Body;

/**
 * 请求网络 测试dagger
 */
public class Test2Activity extends AppCompatActivity {

    @Inject
    public NetManager netManager;

    @Inject
    public Gson mGson;

    private Button btnSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        SakuApplication.getComponent().inject(this);

        btnSubmit = (Button) findViewById(R.id.btn_submit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                visitServer();
            }

        });
    }

    private void visitServer() {

        User  user = new User();
        user.age = 10;
        user.username = "绿芷汀洲";

        final String userJson = mGson.toJson(user);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), userJson);

//        NetManager netManager = SakuApplication.getComponent().getNetManager();

        final Call<ResponseBody> call = netManager.sendUser(body, true);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("lm", " onResponse " + response.body().toString());
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("lm", " onFailure " + t.getMessage());
                Toast.makeText(Test2Activity.this, "联网失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

}
